package com.itheima.interceptor;

import com.itheima.properties.JwtProperties;
import com.itheima.utils.CurrentHolder;
import com.itheima.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @author Waker
 * @description:
 * @create 2025-09-02-11:17
 */
@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    private final JwtProperties jwtProperties;

    public LoginInterceptor(JwtProperties jwtProperties) {
        this.jwtProperties = jwtProperties;
    }

    //在目标方法执行之前执行 返回true放行 返回false拦截
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }
        //获取token
        String token = request.getHeader(jwtProperties.getTokenName());
        // 字符串判空 此处可移除，下方异常包括空字符串情况
        if (!StringUtils.hasLength(token)){
            //为空则 拦截请求 并响应401
            log.info("token为空 请求未登录 响应401");
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return false;
        }
        //2、校验令牌  解析token 判断token是否正确
        //因为token解析失败会抛出异常 所以需要做异常处理
        try {
            log.info("jwt校验:{}", token);
            Claims claims = JwtUtil.parseJWT(jwtProperties.getSecretKey(), token);
            Integer empId = Integer.valueOf(claims.get("id").toString());
            log.info("当前员工id：{}", empId);
            //将jwt中携带的用户id 存储到ThreadLocal
            CurrentHolder.setCurrentId(empId);
            //3、通过，放行
            return true;
        } catch (Exception ex) {
            //4、不通过，响应401状态码
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return false;
        }
    }
}
